// pages/timetable/timetable.js
var util = require('../../utils/util.js');
const app = getApp();
Page({
	data: {
  time:'',
	date: '',
	index: 1,
	text:'',
	num: 0,
	currentTab: 1,
	dateStart: '2019-10-16',
	dateEnd: '2019-10-16',
  countDownInfo: []
	}, /**
  * 生命周期函数--监听页面加载
  */
	onLoad: function (options) {
		let that = this;

		that.getWeekStartDate(0)
		that.getTime()
	},
	//获取本周的开始日期
	getWeekStartDate(numDay) {
		let that = this;
		this.now = new Date();
		this.nowYear = this.now.getYear(); //当前年 
		this.nowMonth = this.now.getMonth(); //当前月 
		this.nowDay = this.now.getDate(); //当前日 
		this.nowDayOfWeek = this.now.getDay(); //今天是本周的第几天 
		this.nowYear += (this.nowYear < 2000) ? 1900 : 0;
		let dateStart = util.formatDate(new Date(this.nowYear, this.nowMonth, this.nowDay - this.nowDayOfWeek + 1 + numDay));
		let dateEnd = util.formatDate(new Date(this.nowYear, this.nowMonth, this.nowDay - this.nowDayOfWeek + 7 + numDay));
		// console.log(dateStart)
		// 获取今天日期
		let now = util.formatDate(new Date(this.nowYear, this.nowMonth, this.nowDay));
		now = now.replace(/-/g, "/");
		now = now.substring(5);
		this.setData({
			dateStart: dateStart,
			dateEnd: dateEnd,
			now: now,
			dates: now,
		})
		// 初始化数据(历史纪录)
		var timestamp = Date.parse(new Date(this.data.dateStart));
		timestamp = timestamp / 1000;
		// console.log(timestamp);
		that.setData({
			timestamp: timestamp
		})
	},

	// 点击上一周
	prevWeek: function (e) {
		var index = this.data.index;
		var text = '';
		if(index<2){
			text = '假期中';
			index = 0
		}else{
			index = index - 1;
		}
		this.setData({
		num :this.data.num - 7,
		index: index,
		text: text
		})
		this.getWeekStartDate(this.data.num);
		console.log(this.data.num)
	},
	// 点击下一周
	nextWeek: function (e) {
		var text = '假期中';
		var num = this.data.num + 7;
		if(num>=0){
			text = ''
		}
		this.setData({
			num: num,
			text: text
		})
		if (num >= 0){
			this.setData({
			index: this.data.index + 1
			})
		}
		this.getWeekStartDate(this.data.num);
		console.log(this.data.num)
	},
  getTime: function(){
    const db = wx.cloud.database();
    db.collection('count_down').where({
      _openid: app.getOpenid(),
    }).get({
					success: res => {
            var countDown = [{}]
            var nowDate = util.formatDate(new Date());
            console.log(nowDate)
            for(var i=0;i<res.data.length;i++){
              var date = new Date(res.data[i].endTime);
              var dateValue = util.formatDate(date);
              countDown[i] = {
                time: util.getDateDiff(dateValue, nowDate), 
                name: res.data[i].name
              }
              console.log(util.getDateDiff(dateValue, nowDate))
            }
            this.setData({
              countDownInfo: countDown
            })
          },
          fail:  err => {
            console.log(err)
          }
    })
  }
})